layui.use(['layer', 'form', 'table', 'configs', 'template', 'laydate', 'util'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        template = layui.template,
        laydate = layui.laydate,
        util = layui.util,
        config = layui.configs;

    //获取表格数据
    getTableData();

    function getTableData() {
        $.ajax({
            // url: config.motorBaseUrl + "",
            url: config.motorBaseUrl + "/monitors/select2/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(result.data);
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //渲染表格
    function renderTable(data) {
        table.render({
            elem: '.settingTable'
            , id: 'monitorsInfo'
            , data: data
            , autoSort: false
            , toolbar: '#toolbarMonitors'
            , defaultToolbar: ['filter']
            , cols: [[
                {field: 'monitorId', title: '监测器Id'}
                , {field: 'strGauge', title: '监测器类型'}
                , {field: 'valueFrom', title: '量程(From)'}
                , {field: 'valueTo', title: '量程(To)'}
                , {field: 'monitorShow', title: '转换器'}
        /*        , {field: 'converterId', title: '所属转换器'}
                , {field: 'bitSn', title: '位序'}*/
                /*, {field: 'strInstallTime', title: '安装时间'}*/
                , {field: 'fixBase', title: '补偿值'}
                , {field: 'inputFrom', title: '输入电流(From)'}
                , {field: 'inputTo', title: '输入电流(To)'}
                , {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#rowOperate'}
            ]]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
        });
    }

    //头工具栏事件--新增
    table.on('toolbar(setMonitorsTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'addMonitors') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增监测器",
                closeBtn: 1,
                anim: 0,
                area: '425px',
                content: $('#newAdd').html(),
                success: function (layero, index) {
                    laydate.render({
                        elem: '#installTime',
                        value: new Date(),
                        format: 'yyyy-MM-dd HH:mm:ss',
                        type: 'datetime',
                        max: formatDate()
                    });
                    getConverter(layero);
                    form.render();
                }
            });
            form.on('submit(AddForm)', function (res) {
                console.log(res.field)
                addMonitors(res.field);
                layer.close(layerIdx);
                return false;
            });
            //取消
            $(".addInfos button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //监听工具条
    table.on('tool(setMonitorsTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                layer.close(index);
                deleteMotors(obj,data.monitorId);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑监测器",
                closeBtn: 1,
                anim: 0,
                area: '420px',
                content: $('#rowEdit').html(),
                success: function (layero, index) {
                    getConverter(layero, function () {
                        form.val("rowEditForm", data);
                        laydate.render({
                            elem: '#installTimeEdit',
                            value: data.installTime == null ? new Date() : new Date(data.installTime),
                            format: 'yyyy-MM-dd HH:mm:ss',
                            type: 'datetime',
                            max: formatDate()
                        });
                    });
                    form.render();
                }
            });
            form.on('submit(rowEditForm)', function (res) {
                //console.log(res.field);
                updateMotors(obj,res.field);
                layer.close(layerIdx);
                return false;
            });
            //取消
            $(".editInfos button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //新增
    function addMonitors(dataObj) {
        $.ajax({
            url: config.motorBaseUrl + "/monitors/add/v1.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteMotors(obj,monitorId) {
        $.ajax({
            url: config.motorBaseUrl + "/monitors/delete/v1.0",
            type: "post",
            datatype: "json",
            data: {
                "monitorId": monitorId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    layer.alert(result.stateMsg);
                    // getTableData();
                    refreshTable('delete',obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //更新
    function updateMotors(obj,data) {
        $.ajax({
            url: config.motorBaseUrl + "/monitors/update/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    // getTableData();
                    refreshTable("update",obj,data);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    function getConverter(layero, callback) {
        $.ajax({
            url: config.motorBaseUrl + "/converter/select/v1.0",
            //url: "converter.json",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    layero.find($(".converter")).html(template("converter-tpl", result));
                    form.render();
                    callback && callback();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    function refreshTable(type,obj,data){
        if(type == "update"){
            obj.update(data); //同步更新缓存对应的值
        }else if(type == "delete"){
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    }
});
